﻿(function ($) {
    bensie = jQuery;
    var api = {
        showShade: function () {
            if ($('#__bsy_ui_shade').size() > 0) { $('#__bsy_ui_shade').remove(); }
            $('<div id="__bsy_ui_shade"></div>').appendTo($(document.body));
        },
        hideShade: function () { $('#__bsy_ui_shade').remove(); },
        __getPosition: function () {
            var dialogContainer = $('#__bsy_dialog');
            var pageViewWidth = $(window).width();
            var pageViewHeight = $(window).height();
            var scrollTop = $(document).scrollTop();
            if (api.isIphone()) {
                pageViewHeight = window.screen.height - 64; //64是iphone微信顶部的ActionBar
                var pageContent = $('#page-content');
                if (pageContent.length > 0) { scrollTop = pageContent.scrollTop(); }
            }
            var scrollLeft = $(document).scrollLeft();
            var width = dialogContainer.outerWidth();
            var height = dialogContainer.outerHeight(true);
            var top = (pageViewHeight - height) / 2;
            var left = (pageViewWidth - width) / 2 + scrollLeft;
            if (!api.isIphone()) { top += scrollTop; }

            return { left: left, top: top };
        },
        __close: function () {
            api.hideShade();
            var id = api.globalVar.__id;
            if (id != '') { $('#' + id).appendTo(api.globalVar.__idPreObject).hide(); }
            api.globalVar.__idPreObject = null;
            $('#__bsy_dialog').remove();
        },
        showLoading: function (options) {
            var defaults = { message: '处理中，请稍后……', timeOut: 0 };
            var ps = $.extend(defaults, options);
            var url = window.location.href;
            if (document.getElementById('__bsy_dialog') != undefined) { return; }
            var dialogContainer = $('<div id="__bsy_dialog" class="__bsy_loading_css"></div>').appendTo($(document.body));
            var dialogContent = $('<div id="__bsy_dialog_content" style="line-height:2rem"><img src="' + api.getBensieUrl() + '/loading.gif" style="vertical-align:middle" /><span style="padding-left:0.5rem">' + ps.message + '</span></div>').appendTo(dialogContainer);

            var bensieSize = api.__getPosition();
            dialogContainer.css({ left: bensieSize.left + 'px', top: bensieSize.top + 'px' });

            api.showShade();
            if (ps.timeOut > 0) { setTimeout(api.closeLoading, ps.timeOut); }
        }, //end of loading
        closeLoading: function () {
            setTimeout(function () {
                api.hideShade();
                $('.__bsy_loading_css').remove();
            }, 500);
        },
        globalVar: { __id: '', __idPreObject: null, __pageIndex: 2 }
    };
    bensie.loading = { show: api.showLoading, close: api.closeLoading };
})($);
